package cn.jhc.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;

import cn.jhc.bean.City;
import cn.jhc.bean.Province;

import android.util.Xml;

public class XMLPullService {

	public static List<Province> getProvince() throws Exception {
		InputStream xml=XMLPullService.class.getClassLoader().getResourceAsStream("provinces.xml");
		XmlPullParser pullParser = Xml.newPullParser();
		pullParser.setInput(xml, "utf-8");
		List<Province> provinces=null;
		int event = pullParser.getEventType();
		Province province = null;
		int pID;
		String provinceName;
		while (event!=XmlPullParser.END_DOCUMENT) {
			switch (event) {
				case XmlPullParser.START_DOCUMENT:
					provinces=new ArrayList<Province>();
					break;
				case XmlPullParser.START_TAG:
					if("Province".equals(pullParser.getName())){
						province=new Province();
						pID=new Integer(pullParser.getAttributeValue(0));
						provinceName=pullParser.getAttributeValue(1);
						province.setId(pID);
						province.setProvinceName(provinceName);
					}
				
					break;
				case XmlPullParser.END_TAG:
					if("Province".equals(pullParser.getName())){
						provinces.add(province);
					}
				
					break;
				default:
					break;
			}
			event = pullParser.next();
		}

		return provinces;
	}
	
	public static List<City> getCity(int pID) throws Exception {
		InputStream xml=XMLPullService.class.getClassLoader().getResourceAsStream("cities.xml");
		XmlPullParser pullParser = Xml.newPullParser();
		pullParser.setInput(xml, "utf-8");
		List<City> citys=null;
		int event = pullParser.getEventType();
		int cID;
		String cityName;
		City city = null;
		while (event!=XmlPullParser.END_DOCUMENT) {
			switch (event) {
				case XmlPullParser.START_DOCUMENT:
					citys=new ArrayList<City>();
					break;
				case XmlPullParser.START_TAG:
					if("City".equals(pullParser.getName())){
						int city_pID=new Integer(pullParser.getAttributeValue(2));
						city=null;
						if(pID==city_pID){
							city=new City();
							cID=new Integer(pullParser.getAttributeValue(0));
							cityName=pullParser.getAttributeValue(1);
							city.setId(cID);
							city.setCityName(cityName);
							
						}
					}
					break;
				case XmlPullParser.END_TAG:
					if("City".equals(pullParser.getName())){
						if(city!=null)
							citys.add(city);
					}
				
					break;
				default:
					break;
			}
			event = pullParser.next();
		}

		return citys;
	}
}
